//
//  GeoViewController.m
//  Runone
//
//  Created by runone01 on 16/10/27.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "GeoViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "ReGeocodeAnnotation.h"
#import "CommonUtility.h"
#import "Define.h"
#import "MANaviAnnotationView.h"
#import "UITextField+ToolBar.h"
#import "POIListViewController.h"

#define RightCallOutTag 1
#define LeftCallOutTag 2

@interface GeoViewController ()<MAMapViewDelegate,UIGestureRecognizerDelegate,AMapSearchDelegate,UITextFieldDelegate,UIPopoverPresentationControllerDelegate,UISearchBarDelegate>
@property (nonatomic, strong) MAMapView *mapView;//地图
@property (nonatomic, strong)MAPointAnnotation *pointAnnotation;
@property(nonatomic,strong)AMapSearchAPI *search;
@property (nonatomic, strong) ReGeocodeAnnotation *annotation;
@property(nonatomic,strong)ReGeocodeAnnotation *reGeocodeAnnotation;
//@property(nonatomic,strong)UITextField *localTF;
@property(nonatomic,strong)UISearchBar *localTF;
@property(nonatomic,strong)NSMutableArray *poiArray;
@property(nonatomic,strong)POIListViewController *poiListModel;
@property(nonatomic,strong)NSArray *tempArray;
@end

@implementation GeoViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadMapView];
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
//    [_localTF setTextFieldInputAccessoryView:_localTF frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    
    _localTF = [[UISearchBar alloc] init];
    _localTF.placeholder          = @"请输入搜索的关键字";
    self.navigationItem.titleView = _localTF;
    _localTF.delegate             = self;
    [_localTF becomeFirstResponder];
    self.navigationItem.titleView = _localTF;
    
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"确 定" style:UIBarButtonItemStylePlain target:self action:@selector(returnVC)];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"返 回" style:UIBarButtonItemStylePlain target:self action:@selector(ReturnVC)];
    [self addSearchBar];
    _poiArray=[[NSMutableArray alloc] init];

    // Do any additional setup after loading the view from its nib.
}


-(void)ReturnVC
{
    if (_TitleBlock!=nil) {
        _TitleBlock(@" ");
    }
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self datePick];
    _poiListModel.poiName=searchText;
    
    [self presentViewController:_poiListModel animated:YES completion:nil];
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [self datePick];
    _poiListModel.poiName=searchBar.text;
    
    [self presentViewController:_poiListModel animated:YES completion:nil];
}

-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}

-(void)datePick {
    
    _poiListModel=[[POIListViewController alloc] init];
    __weak typeof(self) weakSelf = self;
    _poiListModel.addressBlock=^(NSString *str){
        weakSelf.localTF.text=str;
    };
    _poiListModel.modalPresentationStyle=UIModalPresentationPopover;
    _poiListModel.popoverPresentationController.sourceView=self.navigationItem.titleView;
    _poiListModel.popoverPresentationController.sourceRect=CGRectMake(180, 150, 0, 0);
    _poiListModel.popoverPresentationController.permittedArrowDirections=NO;
    _poiListModel.popoverPresentationController.delegate=self;
    
}

-(void)addSearchBar {
////    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(30, 0, [UIScreen mainScreen].bounds.size.width -  60, 35)];
////    view.backgroundColor = [UIColor clearColor];
//    //view.backgroundColor=[UIColor greenColor];
//    _localTF=[[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 280, 30)];
//    _localTF.backgroundColor=[UIColor whiteColor];
//    _localTF.tintColor=[UIColor blackColor];
//    _localTF.delegate=self;
////    UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
////    [btn setImage:[UIImage imageNamed:@"sousuo.png"] forState:UIControlStateNormal];
////    _localTF.leftView=btn;
////    _localTF.leftViewMode=UITextFieldViewModeAlways;
////    _localTF.clearButtonMode=UITextFieldViewModeAlways;
////    [view addSubview:_localTF];
//    self.navigationItem.titleView=_localTF;
    
  
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[[UIView alloc] init]];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(navigationBackClick)];
}

-(void)viewWillDisappear:(BOOL)animated{
    [_mapView removeAnnotation:_reGeocodeAnnotation];
}

-(void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate
{
    [self.mapView removeAnnotation:_reGeocodeAnnotation];
    [self searchReGeocodeWithCoordinate:coordinate];
}

- (void)searchReGeocodeWithCoordinate:(CLLocationCoordinate2D)coordinate {
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    
    regeo.location                    = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    regeo.requireExtension            = YES;
    
    [self.search AMapReGoecodeSearch:regeo];
}

- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if (response.regeocode != nil)
    {
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(request.location.latitude, request.location.longitude);
        _reGeocodeAnnotation = [[ReGeocodeAnnotation alloc] initWithCoordinate:coordinate
                                                                                         reGeocode:response.regeocode];
        
        [self.mapView addAnnotation:_reGeocodeAnnotation];
        NSString *title=_reGeocodeAnnotation.title;
        NSString *com=@",";
        NSString *subTitle=_reGeocodeAnnotation.subtitle;
        NSString *local=[title stringByAppendingString:com];
        NSString *localString=[local stringByAppendingString:subTitle];
        _localTF.text=localString;

        NSLog(@"%@,%@",_reGeocodeAnnotation.title,_reGeocodeAnnotation.subtitle);
        [self.mapView selectAnnotation:_reGeocodeAnnotation animated:YES];
    }
    else /* from drag search, update address */
    {
        [self.annotation setAMapReGeocode:response.regeocode];
        [self.mapView selectAnnotation:self.annotation animated:YES];
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_localTF resignFirstResponder];
}

- (void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    if ([view.annotation isKindOfClass:[ReGeocodeAnnotation class]])
    {
        
         if([control tag] == LeftCallOutTag)
        {
            AMapNaviConfig * config = [[AMapNaviConfig alloc] init];
            config.destination    = view.annotation.coordinate;
            config.appScheme      = [CommonUtility getApplicationScheme];
            config.appName        = [CommonUtility getApplicationName];
            config.strategy       = AMapDrivingStrategyShortest;
            
            if(![AMapURLSearch openAMapNavigation:config])
            {
                [AMapURLSearch getLatestAMapApp];
            }
        }
    }
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[ReGeocodeAnnotation class]])
    {
        static NSString *invertGeoIdentifier = @"invertGeoIdentifier";
        
        MANaviAnnotationView *poiAnnotationView = (MANaviAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:invertGeoIdentifier];
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MANaviAnnotationView alloc] initWithAnnotation:annotation
                                                                 reuseIdentifier:invertGeoIdentifier];
        }
        
        poiAnnotationView.animatesDrop   = YES;
        poiAnnotationView.canShowCallout = YES;
        poiAnnotationView.draggable      = YES;
        
        //show detail by right callout accessory view.
        poiAnnotationView.rightCalloutAccessoryView     = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        poiAnnotationView.rightCalloutAccessoryView.tag = RightCallOutTag;
        
        //call online navi by left accessory.
        poiAnnotationView.leftCalloutAccessoryView.tag  = LeftCallOutTag;
        
        return poiAnnotationView;
    }
    
    return nil;
}


- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"Error: %@", error);
}

-(void)loadMapView
{
    [AMapServices sharedServices].apiKey = GETGAODEPAIKEY;
    
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
    _mapView.delegate = self;
    
    _mapView.showsCompass = NO;
    _mapView.showsScale= NO;
    
    _mapView.showsUserLocation=YES;
    [_mapView setUserTrackingMode: MAUserTrackingModeFollow animated:YES];
    [self.view addSubview:_mapView];
//    
//    //长按屏幕，添加大头针
//    UITapGestureRecognizer *Lpress = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(LongPressClick:)];
//    Lpress.delegate = self;
//    [self.mapView addGestureRecognizer:Lpress];
    
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

//-(void)creatAnnotion:(CLLocationCoordinate2D)touchPoint
//{
//    _pointAnnotation = [[MAPointAnnotation alloc] init];
//    _pointAnnotation.coordinate=touchPoint;
//    //_mapView.centerCoordinate=touchPoint;
//    [_mapView addAnnotation:_pointAnnotation];
//    
//}

////长按事件响应
//-(void)LongPressClick:(UITapGestureRecognizer *)gestureRecognizer
//{
//    [_mapView removeAnnotation:_pointAnnotation];
//    //坐标转换
//    CGPoint touchPoint = [gestureRecognizer locationInView:self.mapView];
//    CLLocationCoordinate2D touchMapCoordinate = [self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];
//    
//    if (self.FloatBlock!=nil) {
//        self.FloatBlock([NSString stringWithFormat:@"%f",touchMapCoordinate.latitude],[NSString stringWithFormat:@"%f",touchMapCoordinate.longitude]);
//    }
//    
//    NSLog(@"%f,%f",touchMapCoordinate.latitude,touchMapCoordinate.longitude);
//    [self creatAnnotion:touchMapCoordinate];
//    if(touchMapCoordinate.latitude&&touchMapCoordinate.longitude){
//       
//    }
//    
//}

-(void)returnVC
{
    [_localTF resignFirstResponder];
    if (_TitleBlock!=nil) {
        _TitleBlock(_localTF.text);
    }
     [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
